local tuwei = fk.CreateSkill {
  name = "tuwei",
}

tuwei:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and
      table.find(player.room.alive_players, function(p) return player:inMyAttackRange(p) and not p:isNude() end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getOtherPlayers(player, false), function(p)
      return player:inMyAttackRange(p) and not p:isNude() end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, #targets, "#tuwei-choose:::"..#targets, self.name, true)
    if #tos > 0 then
      event:setCostData(self,tos)
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:sortPlayersByAction(event:getCostData(self))
    local mark = player:getTableMark("tuwei-turn")
    for _, id in ipairs(event:getCostData(self)) do
      if player.dead then return end
      local p = room:getPlayerById(id)
      if not p.dead then
        table.insertIfNeed(mark, id)
        local card = room:askForCardChosen(player, p, "he", self.name)
        room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player)
      end
    end
    room:setPlayerMark(player, "tuwei-turn", mark)
  end,
})
tuwei:addEffect(fk.TurnEnd, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("tuwei-turn") ~= 0 and not player:isNude()
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local mark = player:getMark("tuwei-turn")
    room:sortPlayersByAction(mark)
    for _, id in ipairs(mark) do
      if player.dead or player:isNude() then return end
      local p = room:getPlayerById(id)
      if not p.dead then
        local events = player.room.logic:getActualDamageEvents(1, function(e)
          local damage = e.data
          return p == damage.to
        end, Player.HistoryTurn)
        if #events == 0 then
          room:doIndicate(id, {player.id})
          local card = room:askForCardChosen(p, player, "he", "tuwei")
          room:moveCardTo(card, Card.PlayerHand, p, fk.ReasonPrey, "tuwei", nil, false, room:getPlayerById(id))
        end
      end
    end
  end,
})
return tuwei